package me.firstapp.api.bbs;

import java.util.Date;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.wordnik.swagger.annotations.Api;
import com.wordnik.swagger.annotations.ApiOperation;

import me.firstapp.api.base.BaseApi;
import me.firstapp.common.exception.ServiceException;
import me.firstapp.common.exception.StatusHouse;
import me.firstapp.common.json.JsonPage;
import me.firstapp.common.json.PageObject;
import me.firstapp.common.json.SingleObject;
import me.firstapp.common.utils.DateUtils;
import me.firstapp.common.utils.Page;
import me.firstapp.common.utils.ResponseUtils;
import me.firstapp.module.bbs.Member;
import me.firstapp.module.shop.ShoppingCart;
import me.firstapp.service.bbs.MemberService;
import me.firstapp.service.shop.ShoppingCartService;

@Controller
@RequestMapping(value = "/member")
@Api(value = "/member", description = "用户相关接口")
public class MemberApi extends BaseApi {

	@Autowired
	private MemberService memberService;

	@Autowired
	private ShoppingCartService shoppingCartService;

	@Autowired
	private StringRedisTemplate stringRedisTemplate;

	@RequestMapping(value = "login.do", method = RequestMethod.POST)
	@ApiOperation(value = "用户登录", notes = "用户登录")
	public void executeLogin(String mobile, String email, String name, String password, HttpServletRequest request,
			HttpServletResponse response) {
		SingleObject<Member> resultJsonObject = new SingleObject<Member>();
		try {
			Long apiClientId = (Long) request.getAttribute("apiClientId");
			Member member = memberService.executeLogin(mobile, email, name, password, apiClientId);
			ShoppingCart shoppingCart = shoppingCartService.findMemberShoppingCart(member.getId(), false, apiClientId);
			member.setShoppingCart(shoppingCart);
			resultJsonObject.setStatusObject(StatusHouse.COMMON_STATUS_OK);
			resultJsonObject.setObject(member);
		} catch (ServiceException e) {
			resultJsonObject.setStatusObject(e.getStatusObject());
		} catch (Exception e) {
			e.printStackTrace();
			resultJsonObject.setStatusObject(StatusHouse.COMMON_STATUS_ERROR);
		}
		ResponseUtils.renderJson(response, resultJsonObject);
	}

	@RequestMapping(value = "register.do", method = RequestMethod.POST)
	@ApiOperation(value = "用户注册", notes = "用户注册")
	public void executeRegister(String mobile, String email, String name, String password, String code,
			HttpServletRequest request, HttpServletResponse response) {
		SingleObject<Member> resultJsonObject = new SingleObject<Member>();
		try {
			Long apiClientId = (Long) request.getAttribute("apiClientId");
			verifyCode(stringRedisTemplate, code, email);
			Member member = memberService.addMember(name, password, null, email, mobile, null, null, apiClientId);
			ShoppingCart shoppingCart = shoppingCartService.findMemberShoppingCart(member.getId(), false, apiClientId);
			member.setShoppingCart(shoppingCart);
			resultJsonObject.setStatusObject(StatusHouse.COMMON_STATUS_OK);
			resultJsonObject.setObject(member);
		} catch (ServiceException e) {
			resultJsonObject.setStatusObject(e.getStatusObject());
		} catch (Exception e) {
			e.printStackTrace();
			resultJsonObject.setStatusObject(StatusHouse.COMMON_STATUS_ERROR);
		}
		ResponseUtils.renderJson(response, resultJsonObject);
	}

	@RequestMapping(value = "findMemberById.do", method = RequestMethod.GET)
	@ApiOperation(value = "通过id获取用户", notes = "通过id获取用户")
	public void executeFindMemberById(Long memberId, HttpServletRequest request, HttpServletResponse response) {
		SingleObject<Object> resultJsonObject = new SingleObject<Object>();
		try {
			Long apiClientId = (Long) request.getAttribute("apiClientId");
			Member member = memberService.findMemberById(memberId, apiClientId);
			if (member != null) {
				ShoppingCart shoppingCart = shoppingCartService.findMemberShoppingCart(memberId, false, apiClientId);
				member.setShoppingCart(shoppingCart);
			}
			resultJsonObject.setObject(member);
			resultJsonObject.setStatusObject(StatusHouse.COMMON_STATUS_OK);
		} catch (ServiceException e) {
			resultJsonObject.setStatusObject(e.getStatusObject());
		} catch (Exception e) {
			e.printStackTrace();
			resultJsonObject.setStatusObject(StatusHouse.COMMON_STATUS_ERROR);
		}
		ResponseUtils.renderJson(response, resultJsonObject);
	}

	@RequestMapping(value = "updateMemberInfo.do", method = RequestMethod.POST)
	@ApiOperation(value = "更新用户信息", notes = "更新用户信息")
	public void updateMemberInfo(Long memberId, String avatar, String url, String signature, Integer status,
			HttpServletRequest request, HttpServletResponse response) {
		SingleObject<Object> resultJsonObject = new SingleObject<Object>();
		try {
			Long apiClientId = (Long) request.getAttribute("apiClientId");
			Member member = memberService.updateMemberInfo(memberId, avatar, url, signature, status, apiClientId);
			resultJsonObject.setStatusObject(StatusHouse.COMMON_STATUS_OK);
			resultJsonObject.setObject(member);
		} catch (ServiceException e) {
			resultJsonObject.setStatusObject(e.getStatusObject());
		} catch (Exception e) {
			e.printStackTrace();
			resultJsonObject.setStatusObject(StatusHouse.COMMON_STATUS_ERROR);
		}
		ResponseUtils.renderJson(response, resultJsonObject);
	}

	@RequestMapping(value = "alterLoginPassword.do", method = RequestMethod.POST)
	@ApiOperation(value = "修改登录密码", notes = "修改登录密码")
	public void alterLoginPassword(Long memberId, String oldPassword, String newPassword, String code,
			HttpServletRequest request, HttpServletResponse response) {
		SingleObject<Object> result = new SingleObject<>();
		try {
			Long apiClientId = (Long) request.getAttribute("apiClientId");
			Member member = memberService.findMemberById(memberId, apiClientId);
			if (member != null) {
				verifyCode(stringRedisTemplate, code, member.getEmail());
			}
			memberService.updateMemberPassword(memberId, oldPassword, newPassword, apiClientId);
			result.setStatusObject(StatusHouse.COMMON_STATUS_OK);
		} catch (ServiceException e) {
			result.setStatusObject(e.getStatusObject());
		} catch (Exception e) {
			e.printStackTrace();
			result.setStatusObject(StatusHouse.COMMON_STATUS_ERROR);
		}
		ResponseUtils.renderJson(response, result);
	}

	@RequestMapping(value = "findMemberPage.do", method = RequestMethod.POST)
	@ApiOperation(value = "分页查询用户", notes = "分页查询用户")
	public void findMemberPage(@RequestBody Map<String, Object> searchParams,
			@RequestParam(value = "pageNo", required = true, defaultValue = "1") Integer pageNo,
			@RequestParam(value = "pageSize", required = true, defaultValue = "20") Integer pageSize, String sortParam,
			String sortType, Long startTime, Long endTime, HttpServletRequest request, HttpServletResponse response) {
		PageObject<Member> result = new PageObject<>();
		try {
			Long apiClientId = (Long) request.getAttribute("apiClientId");
			Date startDate = null;
			if (startTime != null) {
				startDate = DateUtils.getDateFromTimeStamp(String.valueOf(startTime), "yyyy-MM-dd");
			}
			Date endDate = null;
			if (endTime != null) {
				endDate = DateUtils.getDateFromTimeStamp(String.valueOf(endTime), "yyyy-MM-dd");
			}
			Page<Member> memberPage = memberService.findMemberPage(pageNo, pageSize, searchParams, sortParam, sortType,
					startDate, endDate, apiClientId);
			JsonPage<Member> jsonPage = new JsonPage<Member>();
			jsonPage.setList(memberPage.getEntities());
			jsonPage.setPageNo(memberPage.getPageNo());
			jsonPage.setPageSize(memberPage.getPageSize());
			jsonPage.setTotalCount(memberPage.getEntityCount());
			result.setStatusObject(StatusHouse.COMMON_STATUS_OK);
			result.setPage(jsonPage);
		} catch (ServiceException e) {
			result.setStatusObject(e.getStatusObject());
		} catch (Exception e) {
			e.printStackTrace();
			result.setStatusObject(StatusHouse.COMMON_STATUS_ERROR);
		}
		ResponseUtils.renderJson(response, result);
	}

	@RequestMapping(value = "resetPassword.do", method = RequestMethod.POST)
	@ApiOperation(value = "重置密码", notes = "重置密码")
	public void resetPassword(String email, String code, String newPassword, HttpServletRequest request,
			HttpServletResponse response) {
		SingleObject<Object> result = new SingleObject<>();
		try {
			Long apiClientId = (Long) request.getAttribute("apiClientId");
			verifyCode(stringRedisTemplate, code, email);
			memberService.executeResetPassword(email, newPassword, apiClientId);
			result.setStatusObject(StatusHouse.COMMON_STATUS_OK);
		} catch (ServiceException e) {
			result.setStatusObject(e.getStatusObject());
		} catch (Exception e) {
			e.printStackTrace();
			result.setStatusObject(StatusHouse.COMMON_STATUS_ERROR);
		}
		ResponseUtils.renderJson(response, result);
	}
}
